#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "listReader.h"

#include <QPrinter>
#include <QPainter>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    lr = new listReader;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setColumn(int c, QString &s)
{
    if (ui->tbinfo->item(0, c) == NULL)
    {
        QTableWidgetItem *item = new QTableWidgetItem;

        ui->tbinfo->setItem(0, c, item);
    }
    ui->tbinfo->item(0, c)->setText(s);
}

void MainWindow::showRow(QMap <QString, QString> &val)
{
    int cn = 0;

    setColumn(cn++, val["客户单位"]);
    setColumn(cn++, val["姓名"]);
    setColumn(cn++, val["零售店地址"]);
    setColumn(cn++, val["专卖许可证号"]);
    setColumn(cn++, val["卡号"]);
}

#include <QFileDialog>

void MainWindow::on_pbload_clicked()
{
    QString fn;

    fn = QFileDialog::getOpenFileName(this, "选择照片目录",
                                       "./",                              "*.xlsx");
    if (!fn.isEmpty())
    {
        lr->load(fn);
        ui->line1->clear();
        ui->line2->clear();
    }
}

void MainWindow::showCard()
{
    int cnt;
    QString s;

    ui->line1->clear();
    ui->line2->clear();

    for (cnt = 0; cnt < ui->tbinfo->columnCount() - 1; cnt ++)
    {
        QString t;

        s = ui->tbinfo->horizontalHeaderItem(cnt)->text();
        s += "：";
        t = ui->tbinfo->item(0, cnt)->text();
        if (!t.isEmpty())
            s += t;
        else
            s = " ";

        ui->line1->appendPlainText(s);
        s.clear();
    }

    s = ui->tbinfo->item(0, cnt)->text();
    for (int i = 0, pos = 4; i < 4; i ++)
    {
        s.insert(pos, ' ');
        pos += 4;
        pos ++;
    }
    ui->line2->appendPlainText(s);
}

void MainWindow::on_pbnext_clicked()
{
    QMap <QString,QString> val;

    if (lr->next(val))
    {
        showRow(val);
        showCard();
    }
}

#include <QTextBlock>
#include <QPrintDialog>

void MainWindow::on_pbprint_clicked()
{
    QPrinter p;

    QString s;
    QPoint pos;
    QPlainTextEdit *l;
    QTextBlock tb;
    QPointF pf;
    QPrintDialog pd(&p, this);

    if (pd.exec() == 0)
        return;

    QPainter d(&p);
    d.setFont(ui->line1->font());
    pos = ui->line1->pos();
    l = ui->line1;
    for (int i = 0; i < l->blockCount(); i ++)
    {
        tb = l->document()->findBlockByNumber(i);
        s = tb.text();
        d.drawText(pos, s);
        pos.setY(pos.y() + 16);
    }

    l = ui->line2;
    d.setFont(l->font());
    pos = l->pos();
    tb = l->document()->firstBlock();
    s = tb.text();
    d.drawText(pos, s);
}
